package com.iqik.sc.controller;

import com.iqik.sc.ns.service.AuthCodeService;
import com.iqik.sc.ns.service.EmailServer;
import com.iqik.sc.ns.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/code")
public class AuthCodeController {

    private final AuthCodeService authCodeService;

    private final EmailServer emailServer;

    private final UserService userService;

    @Autowired
    public AuthCodeController(AuthCodeService authCodeService, EmailServer emailServer, UserService userService) {
        this.authCodeService = authCodeService;
        this.emailServer = emailServer;
        this.userService = userService;
    }

    /**
     * /create/{email} true/false ⽣成验证码并发送到对应邮箱，成功true，失败
     */
    @RequestMapping("/create/{email}")
    public String createCode(@PathVariable(value = "email") String email) {

        if (Boolean.valueOf(userService.isRegister(email))) {
            return "false";
        }
        String authCode = authCodeService.createAuthCode(email);
        return String.valueOf(emailServer.sendCode(email, authCode));
    }

    /**
     * /code/validate/{email}/{code}
     * 校验验证码是否正确，0正确1错误2超时
     */
    @RequestMapping("/validate/{email}/{code}")
    public String verityCode(@PathVariable(value = "email") String email,
                             @PathVariable(value = "code") String code) {

        return String.valueOf(authCodeService.verityAuthCode(email, code));
    }
}
